/**
 * 15-600: Java and J2EE
 * Instructor: Jeff Eppinger
 * Done By:	Mohammad al Khani
 * Date Dec 10, 2011
 */

package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import model.BookmarkDAO;
import model.Model;
import model.UserDAO;

import org.mybeans.form.FormBeanFactory;

import dataBeans.Bookmark;
import dataBeans.User;
import formBean.AddBookmarksForm;

public class AddBookmarkAction extends Action{
	private FormBeanFactory<AddBookmarksForm> formBeanFactory = FormBeanFactory.getInstance(AddBookmarksForm.class);
	private UserDAO userDAO;
	private BookmarkDAO bookmarkDAO;
	
	public AddBookmarkAction(Model model){
	
	}
	
	public String getName(){ 
		return "addBookmark.do"; 
	}
    
    public String perform(HttpServletRequest request) {
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        
        try {
        	//TODO:check for errors
	    	AddBookmarksForm form = formBeanFactory.create(request);
	        request.setAttribute("form",form);
	        
	        if(!form.isPresent()){
	        	return "manageUserBookmarks.jsp";
	        }
	        
	        errors.addAll(form.getValidationErrors());
	        if(errors.size() > 0){
	        	return "manageUserBookmarks.jsp";
	        }
	        
	        User user = (User)request.getSession().getAttribute("user");
	        if(user != null){
	        	bookmarkDAO = new BookmarkDAO();
	        	bookmarkDAO.addBookmark(user.getUserId(), form.getUrl(), form.getComment());
	        	Bookmark[] userBookmarks = bookmarkDAO.getUserBookmarks(user.getUserId());
	        	request.getSession().setAttribute("userBookmarks", userBookmarks);
	        	request.setAttribute("form",form);
	        }else{
	        	System.err.println("user isn't there");
	        }
        }catch(Exception e){
        	e.printStackTrace();
        }
        String webapp = request.getContextPath();
		return webapp + "/manage.do";
    	//return "manageUserBookmarks.jsp";
    }
}
